﻿#include "YCameraRecord.h"
#include "../task/YDemuxerTask.h"
#include "../task/YMuxerTask.h"
#include <chrono>
#include <iomanip>
#include <sstream>
using namespace std;
using namespace chrono;

// 生成存储的视频文件名
static std::string GetFileName(string path)
{
    stringstream ss;
    //获取当前时间
    auto t = system_clock::to_time_t(system_clock::now());
    auto time_str = put_time(localtime(&t), "%Y_%m_%d_%H_%M_%S");
    ss << path << "/" << "cam_" << time_str << ".mp4";
    return ss.str();
}

void YCameraRecord::Working()
{
    YDemuxerTask demux;
    YMuxerTask mux;
    if (rtsp_url_.empty())
    {
        LOGERROR("open rtsp url failed!");
        return;
    }

    //自动重连
    while (!isExit_)
    {
        if (demux.Open(rtsp_url_)) //最坏情况阻塞1秒
        {
            break;
        }
        MSleep(3000);//3秒钟重连一次
        continue;
    }
    //视频参数
    auto vpara = demux.CopyVideoPara();
    if (!vpara)
    {
        LOGERROR("demux.CopyVideoPara failed!");
        //需要考虑demux 资源释放的问题
        demux.Stop();
        return;
    }
    //启动解封装线程，提前启动，防止超时
    demux.Start();

    //获取音频参数
    auto apara = demux.CopyAudioPara();

    AVCodecParameters* para = nullptr;  //音频参数
    AVRational* timebase = nullptr;     //音频时间基数
    if (apara)
    {
        para = apara->para;
        timebase = apara->time_base;
    }

    //打开了封装
    if (!mux.Open(GetFileName(save_path_).c_str(),
        vpara->para, vpara->time_base,//视频参数
        para, timebase))            //音频参数
    {
        LOGERROR("mux.Open rtsp_url_ failed!");
        demux.Stop();
        mux.Stop();
        return;
    }
    demux.setNext(&mux);
    mux.Start();

    //当前时间
    auto cur = NowMs();

    while (!isExit_)
    {
        //定时创建新的文件
        if (NowMs() - cur > file_sec_ * 1000)
        {
            cur = NowMs();
            mux.Stop(); //停止存储，写入索引
            //打开了封装
            if (!mux.Open(GetFileName(save_path_).c_str(),
                vpara->para, vpara->time_base,//视频参数
                para, timebase))            //音频参数
            {
                LOGERROR("mux.Open rtsp_url_ failed!");
                demux.Stop();
                mux.Stop();
                return;
            }
            mux.Start();
        }

        MSleep(10);
    }

    mux.Stop();
    demux.Stop();
}

YCameraRecord::YCameraRecord()
{
}

YCameraRecord::~YCameraRecord()
{
}
